package servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import entity.User;
import service.UserService;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1.验证验证码
		String userCode =request.getParameter("userCode");
		String serverCode=(String)request.getSession().getAttribute("serverCode");
		if(!serverCode.equalsIgnoreCase(userCode)) {
			request.setAttribute("codeError", "验证码输入错误");
			request.getRequestDispatcher("/client/register.jsp").forward(request, response);
			return;
		}
		//2.封装参数到user
		User user =new User();
		try {
			BeanUtils.populate(user,request.getParameterMap());
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}					
		//3.调用UserService的注册方法
		UserService service =new UserService();
		try {
			service.register(user);
			//注册成功
			response.sendRedirect(request.getContextPath()+"/client/registersuccess.jsp");
		} catch (Exception e) {
			// TODO: handle exception
			String error =e.getMessage();//注册失败
			response.getWriter().write(error);
		}
		
		
		
		
		
		
	}

}
